package com.itany.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.book.mapper.RoleMapper;
import com.itany.book.pojo.Permission;
import com.itany.book.pojo.Role;
import com.itany.book.service.RoleService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author:yaozhiyuan0117@163.com
 * Time:2019/12/26 18:16
 * Describe:
 * version:1.0
 */

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Role> findAll(Integer page, Integer rows, String name) {
        PageHelper.startPage(page,rows);
        List<Role> roles= roleMapper.selectByCondition(name);
        System.out.println("=====================");
        for (Role role: roles){
            List<Permission> permissions = role.getPermissions();
            for (Permission p: permissions){
                System.out.println(p);
            }
        }
        PageInfo<Role> info = new PageInfo<>(roles);
        return info;
    }

    @Override
    public Role findById(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void modifyRole(Integer id, String name, String[] permissions) {
        // 1. 修改用户名
        roleMapper.modifyRoleName(id,name);
        // 2，从role-permission删除所有roleid为id的
        roleMapper.deleteRoleAllPermission(id);
        // 3. for循环插入id permissions
        for (String permissionId : permissions){
            System.out.println(permissionId);
            roleMapper.insertRolePermission(id, Integer.parseInt(permissionId));
        }
    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Role> findRoles() {
        //这样会多查很多信息，但是不会错！应该换一个，懒了
        return roleMapper.selectByCondition("");
    }
}